﻿using System.Web.WebPages;
using WebMatrix.WebData;

namespace Account
{
    /// <summary>
    /// Summary description for PasswordReset
    /// </summary>
    public static class PasswordReset
    {
        public class Model
        {
            public string NewPassword { get; set; }
            public string ConfirmPassword { get; set; }
            public string ResetToken { get; set; }
        }

        public class Error
        {
            public ErrorMessage NewPassword { get; set; }
            public ErrorMessage ConfirmPassword { get; set; }
            public ErrorMessage ResetToken { get; set; }

            public Error()
            {
                NewPassword = ErrorMessage.Nil;
                ConfirmPassword = ErrorMessage.Nil;
                ResetToken = ErrorMessage.Nil;
            }
        }

        public static void  Init(WebPageBase web)
        {
            Model model = web.Page.Model = new Model();
            Error error = web.Page.Errors = new Error();

            model.ResetToken = web.Request.Form["resetToken"] ?? web.Request.QueryString["resetToken"];
            model.NewPassword = web.Request["newPassword"];
            model.ConfirmPassword = web.Request["confirmPassword"];
            
            bool tokenExpired = false;
            web.Page.Success = false;

            if (web.IsPost)
            {
                if (model.NewPassword.IsEmpty())
                {
                    error.NewPassword = web.Error("Please enter a new password.");
                }

                if (model.NewPassword != model.ConfirmPassword)
                {
                    error.ConfirmPassword = web.Error("The password confirmation did not match the new password.");
                }

                if (model.ResetToken.IsEmpty())
                {
                    error.ResetToken = web.Error("Please enter your password reset token. It should have been sent to you in an email.");
                }

                if (web.Page.IsValid)
                {
                    if (WebSecurity.ResetPassword(model.ResetToken, model.NewPassword))
                    {
                        web.Page.Success = true;
                    }
                    else
                    {
                        error.ResetToken = web.Error("The password reset token is invalid.");
                        tokenExpired = true;                        
                    }
                }
            }
        }
    }
}